package pfc.view.view.components.view;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;

import org.apache.log4j.Logger;

public class JFileChooserLastDirectoryAware extends JFileChooser {
	
	private static Logger logger = Logger.getLogger(JFileChooserLastDirectoryAware.class);

     private static final long serialVersionUID = 1L;
     
     private static Map lastDirectoryMap = Collections.synchronizedMap(new HashMap());
     
     public static void initialize(Map directories){
          lastDirectoryMap.putAll(directories);
     }
     
     public static Map getLastDirectoryMap(){
    	 return new HashMap(lastDirectoryMap);
     }
     
     private String lastDirectoryKey;

     public JFileChooserLastDirectoryAware(String lastDirectoryKey) {
          super();
          this.lastDirectoryKey = lastDirectoryKey;
          initialize();
     }

     public JFileChooserLastDirectoryAware(FileSystemView fsv, String lastDirectoryKey) {
          super(fsv);
          this.lastDirectoryKey = lastDirectoryKey;
          initialize();
     }


     private void initialize() {
          if (lastDirectoryKey != null) {
               File currentDirectory = (File) lastDirectoryMap.get(lastDirectoryKey);
               
               if (currentDirectory != null) {
                    setCurrentDirectory(currentDirectory);
               }               
          }
     }
     
     public void setLastDirectory(File file) {
		if (lastDirectoryKey != null) {
			try {
				if (file.isDirectory()) {
					lastDirectoryMap.put(lastDirectoryKey, file);
				} else {
					String fileName = file.getName();
					lastDirectoryMap.put(lastDirectoryKey, new File(fileName.substring(	0, fileName.lastIndexOf(
													File.separator))));
				}
			} catch (Exception e) {
				logger.warn("Nome do arquivo nulo chegando no FileChooser");
			}
		}
	}
     
     
}

